<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul id="todos">
</ul>
<!--没有防抖的版本-->
<!--<script>-->
<!--  let todos = document.querySelector('#todos');-->
<!--  window.onload = function(){-->
<!--    fetch('/todos').then(res=>res.json()).then(response=>{-->
<!--      todos.innerHTML = response.map(item=>`<li "><input value="${item.id}" type="checkbox" ${item.completed?"checked":""}/>${item.text}</li>`).join('');-->
<!--    });-->
<!--  }-->
<!--  function toggle(id){-->
<!--    fetch(`/toggle/${id}`).then(res=>res.json()).then(response=>{-->
<!--      console.log('response',response);-->
<!--    });-->
<!--  }-->
<!--  todos.addEventListener('click',function(event){-->
<!--    let checkbox = event.target;-->
<!--    let id = checkbox.value;-->
<!--    toggle(id);-->
<!--  });-->
<!--</script>-->

<script>
  /*
    点击check切换状态后 2s内如果点击了其它的check 则上一个并不会生效 而是生效当前点击的定时器 如果2秒内没有其它操作 就会切换状态
  */
  let todos = document.querySelector('#todos');
  window.onload = function(){
    fetch('/todos').then(res=>res.json()).then(response=>{
      todos.innerHTML = response.map(item=>`<li "><input value="${item.id}" type="checkbox" ${item.completed?"checked":""}/>${item.text}</li>`).join('');
    });
  }
  function toggle(id){
    fetch(`/toggle/${id}`).then(res=>res.json()).then(response=>{
      console.log('response',response);
    });
  }
  let LazyToggle = (function(id){
    let ids = [];
    let timer;
    return function(id){
      ids.push(id);
      if(timer){
        clearTimeout(timer);
      }
      timer = setTimeout(function(){
        toggle(ids.join(','));
        ids = null;
        clearTimeout(timer);
        timer = null;
      },2000);
    }
  })();
  todos.addEventListener('click',function(event){
    let checkbox = event.target;
    let id = checkbox.value;
    LazyToggle(id);
  });
</script>
</body>
</html>
